package com.nidu.demo.file.storage.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.nidu.demo.common.enums.FileStorageTypeEnum;
import com.nidu.demo.file.storage.FileStorage;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 腾讯云COS文件存储实现
 *
 * @author auto
 */
@Slf4j
@Component
public class TencentCosFileStorage implements FileStorage {

    @Override
    public String upload(MultipartFile file, String path, Map<String, Object> config) {
        try {
            // 获取配置参数
            String secretId = (String) config.get("secretId");
            String secretKey = (String) config.get("secretKey");
            String region = (String) config.get("region");
            String bucketName = (String) config.get("bucketName");
            
            // 创建COS凭证
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            
            // 创建客户端配置
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            
            // 创建COS客户端
            COSClient cosClient = new COSClient(cred, clientConfig);
            
            try {
                // 生成文件名
                String originalFilename = file.getOriginalFilename();
                String extension = "";
                if (originalFilename != null && originalFilename.contains(".")) {
                    extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                }
                String fileName = IdUtil.fastSimpleUUID() + extension;
                
                // 构建对象键
                String objectKey = path + "/" + fileName;
                
                // 设置文件元信息
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(file.getSize());
                metadata.setContentType(file.getContentType());
                
                // 创建上传请求
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectKey, file.getInputStream(), metadata);
                
                // 上传文件
                cosClient.putObject(putObjectRequest);
                
                return objectKey;
                
            } finally {
                cosClient.shutdown();
            }
            
        } catch (IOException e) {
            log.error("腾讯云COS文件上传失败", e);
            throw new RuntimeException("文件上传失败", e);
        }
    }

    @Override
    public void delete(String path, Map<String, Object> config) {
        String secretId = (String) config.get("secretId");
        String secretKey = (String) config.get("secretKey");
        String region = (String) config.get("region");
        String bucketName = (String) config.get("bucketName");
        
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosClient = new COSClient(cred, clientConfig);
        
        try {
            cosClient.deleteObject(bucketName, path);
        } finally {
            cosClient.shutdown();
        }
    }

    @Override
    public String getUrl(String path, Map<String, Object> config) {
        String region = (String) config.get("region");
        String bucketName = (String) config.get("bucketName");
        String customDomain = (String) config.get("customDomain");
        
        if (StrUtil.isNotEmpty(customDomain)) {
            return customDomain + "/" + path;
        } else {
            return "https://" + bucketName + ".cos." + region + ".myqcloud.com/" + path;
        }
    }

    @Override
    public Integer getStorageType() {
        return FileStorageTypeEnum.TENCENT_COS.getType();
    }
}
